﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
//using CommonControls.ClassFiles;
using Microsoft.Advertising.Mobile.UI;
using Helper;
using System.Windows.Threading;
using OnlineVideos.ViewModels;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Phone.Tasks;
using MyToolkit.Phone;
using Common.Library;
using OnlineVideos.Library;
using OnlineVideos.UI;

namespace OnlineVideos.Views
{
    public partial class CricketDetails : PhoneApplicationPage
    {
        private SolidColorBrush adcontrolborder = new SolidColorBrush(Colors.Transparent);
        private BackgroundWorker backgroundWorker;
        CustomizationSettings objCustom = new CustomizationSettings();
        Vidoes objVidoes = new Vidoes();
        DispatcherTimer timer1 = new DispatcherTimer();
        DispatcherTimer timer2 = new DispatcherTimer();
        DispatcherTimer timer3 = new DispatcherTimer();
        List<VideoProperties> objSongList = new List<VideoProperties>();
        OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
        VideoProperties objscoredetails;
        
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        string imgname = "";
        string chapter = "";
        RatingPopup ratepopup = new RatingPopup();
        GalleryPopup gallerypopup = new GalleryPopup();

        public CricketDetails()
        {
            InitializeComponent();
            //pvtMainDetails.Background = Application.Current.Resources["bipivot"] as ImageBrush;
            
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {

                FlurryWP8SDK.Api.EndTimedEvent("CricketDetails Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In CricketDetails.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
                string type = "";


                if (type == "search")
                    NavigationService.RemoveBackEntry();

                YouTube.CancelPlay();
            }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In CricketDetails.cs file.", ex);
            }
        } 
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogEvent("CricketDetails Page", true);
                performanceProgressBar.IsIndeterminate = true;
                LoadAds();
                string id = "";
                //string title = "";
                if (NavigationContext.QueryString.TryGetValue("chapter", out chapter))
                {
                }
                if (NavigationContext.QueryString.TryGetValue("id", out id))
                    App.Id = id;
                {
                    objVidoes.GetCricketTeam1Title(App.Id);
                    LoadPivotTitles();
                    if (App.cricount == 0)
                    {

                        backgroundWorker = new BackgroundWorker();
                        backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
                        backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
                        backgroundWorker.RunWorkerAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In CricketDetails.cs file.", ex);
            }

        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                LoadSummary();
                objSongList = objVidoes.GetSongsLinksOfAMovie(App.Id, false);
                LoadSongsLinks(App.Id);
                objVidoes.GetCriketSectionta(App.Id, App.TeamA);
                lbxcriketCastTeam1.ItemsSource = App.objpropCastta;
                objVidoes.GetCriketSectiontb(App.Id, App.TeamB);
                lbxcriketCastTeam2.ItemsSource = App.objpropCasttb;
                lbxSongsList.Loaded += new RoutedEventHandler(lbxSongsList_Loaded);
                performanceProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in backgroundWorker_RunWorkerCompleted Method In CricketDetails.cs file.", ex);
            }
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {

            try
            {
                objVidoes.LoadFirsthighestInnings(App.Id);
                objVidoes.LoadSeconghighestInnings(App.Id);
                objscoredetails = objVidoes.GetExtraSection(App.Id);
                objVidoes.LoadTeamAbowlSummary(App.Id);
                objVidoes.LoadTeamBbowlSummary(App.Id);
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in backgroundWorker_DoWork Method In CricketDetails.cs file.", ex);
            }
           
        }

        private void LoadSummary()
        {
            LoadExtraSection(App.Id);
            lbxteamAsummary.ItemsSource = App.objproptasum;
            lbxteamBsummary.ItemsSource = App.objproptbsum;
            lbxteamAsummarybowling.ItemsSource = App.objproptabsum;
            lbxteamsummaryBbowling.ItemsSource = App.objproptbbsum;
        }
      
        private void LoadPivotTitles()
        {
            tblkCriketCastTeam1.Text = App.TeamATitle;
            tblkitmCriketCastTeam2.Text = App.TeamBTitle;
            //imgTitle.Style= Application.Current.Resources["PivotTitle"] as Style;
            pvtitmCriketSumarry.Header = Application.Current.Resources["pvtTitleFive"] as string;
            pvtitmSongs.Header = Application.Current.Resources["pvtitmSongsTitle"] as string;
            tblkVideosTitle.Text = objVidoes.GetMovieTitle(App.Id);
        }
        private void LoadAds()
        {
            try
            {
                AdControl adc = new AdControl();
                adc.AdUnitId = Application.Current.Resources["misuid"] as string;
                adc.ApplicationId = Application.Current.Resources["misappid"] as string;
                adc.Width = 480;
                adc.IsAutoRefreshEnabled = true;
                adc.Height = 80;
                adc.BorderBrush = adcontrolborder;
                adstackpl.Children.Add(adc);

                AdControl adc1 = new AdControl();
                adc1.AdUnitId = Application.Current.Resources["misuid"] as string;
                adc1.ApplicationId = Application.Current.Resources["misappid"] as string;
                adc1.Width = 480;
                adc1.IsAutoRefreshEnabled = true;
                adc1.Height = 80;
                adc1.BorderBrush = adcontrolborder;
                adstacriketCastTeam1.Children.Add(adc1);

                AdControl adc2 = new AdControl();
                adc2.AdUnitId = Application.Current.Resources["misuid"] as string;
                adc2.ApplicationId = Application.Current.Resources["misappid"] as string;
                adc2.Width = 480;
                adc2.IsAutoRefreshEnabled = true;
                adc2.Height = 80;
                adc2.BorderBrush = adcontrolborder;
                adstacriketCastTeam2.Children.Add(adc2);
            }
            catch (Exception ex)
            {
                string mess = "Exception in LoadAds Method In CricketDetails file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex.Data);
            }
        }
        private void LoadExtraSection(string id)
        {

            tblkAinningssumary.Text = objscoredetails.Firstinngs;
            tblkBsummaryinnings.Text = objscoredetails.Secondinngs;
            tblkATotsumary.Text = objscoredetails.taTotal;
            txtTeamAtotal.Visibility = Visibility.Visible;
            tblkBTotsumary.Text = objscoredetails.tbTotal;
            txtTeamBtotal.Visibility = Visibility.Visible;
            btnMatchResult.Visibility = Visibility.Visible;
            tblkMatchResult.Text = objscoredetails.MatchResult;
        }

        private void LoadSongsLinks(string id)
        {
            //Songs Links
            if (objSongList.Count > 0)
            {
                lbxSongsList.ItemsSource = objSongList;
                //tblkFavNoSongs.Visibility = Visibility.Collapsed;
            }
            else
                tblkFavNoSongs.Visibility = Visibility.Visible;

        }
        private void lbxcriketCastTeam1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxcriketCastTeam1.SelectedIndex == -1)
                return;
            App.pPid = (lbxcriketCastTeam1.SelectedItem as VideoProperties).PersonId;
          
            NavigationService.Navigate(new Uri("/Views/CastPanorama.xaml?title=cast&pid=" + App.pPid + "&Mid=" + App.Id, UriKind.Relative));
            App.detailtocast++;
            if (App.detailtocast > 1)
            {
             
                NavigationService.RemoveBackEntry();
            }
            lbxcriketCastTeam1.SelectedIndex = -1;
        }
        private void lbxcriketCastTeam2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxcriketCastTeam2.SelectedIndex == -1)
                return;
            App.pPid = (lbxcriketCastTeam2.SelectedItem as VideoProperties).PersonId;
            NavigationService.Navigate(new Uri("/Views/CastPanorama.xaml?title=cast&pid=" + App.pPid + "&Mid=" + App.Id, UriKind.Relative));
            App.detailtocast++;
            if (App.detailtocast > 1)
            {
               
                NavigationService.RemoveBackEntry();
            }
            lbxcriketCastTeam2.SelectedIndex = -1;

        }
        private void lbxSongList_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string Stitle = "";
                IEnumerable<DependencyObject> cboxes = CustomizationSettings.GetChildsRecursive(lbxSongsList);

                foreach (DependencyObject obj in cboxes.OfType<TextBlock>())
                {
                    Type type = obj.GetType();
                    if (type.Name == "TextBlock")
                    {
                        TextBlock cb = obj as TextBlock;
                        if (NavigationContext.QueryString.TryGetValue("Stitle", out Stitle))
                        {
                            if (cb.Text == Stitle)
                                cb.Foreground = new SolidColorBrush(Color.FromArgb(100, 24, 255, 250));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                    Exceptions.SaveOrSendExceptions("Exception in lbxSongList_Loaded Method In CricketDetails.cs file.", ex);
            }


        }
        private TextBlock LoadTextBlock(string text, double fontSize)
        {
            TextBlock tblk = new TextBlock();
            tblk.Text = text;
            tblk.FontSize = fontSize;
            tblk.TextWrapping = TextWrapping.Wrap;
       
            tblk.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            return tblk;
        }

        private void lbxSongsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxSongsList.SelectedIndex == -1)
                return;
            History objHistory = new History();
            objHistory.SaveSongHistory((lbxSongsList.SelectedItem as VideoProperties).MovieId, (lbxSongsList.SelectedItem as VideoProperties).ChapterNo);
            PhoneHelper.LoadYoutubeVideo((lbxSongsList.SelectedItem as VideoProperties).Link);
            lbxSongsList.SelectedIndex = -1;
            
        }
        private void btnBrokenSong_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            if (selectedListBoxItem == null)
                return;
            string id = (selectedListBoxItem.Content as VideoProperties).MovieId;

            NavigationService.Navigate(new Uri("/Views/Feedback.xaml?id=" + (selectedListBoxItem.Content as VideoProperties).MovieId + "&chno=" + (selectedListBoxItem.Content as VideoProperties).ChapterNo + "&title=" + objVidoes.GetMovieTitle1(id) + "&LinkType=Song" + "&uri=" + (selectedListBoxItem.Content as VideoProperties).Link, UriKind.Relative));
        }
        private void btnFavSong_Click(object sender, RoutedEventArgs e)
        {

            ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            if (selectedListBoxItem == null)
                return;

            objVidoes.SaveFavoriteSongs((selectedListBoxItem.Content as VideoProperties).MovieId, (selectedListBoxItem.Content as VideoProperties).SongID);
            objSongList = objVidoes.GetSongsLinksOfAMovie(App.Id, false);
            lbxSongsList.ItemsSource = objSongList;

        }

        private void btnMatchResult_Click(object sender, RoutedEventArgs e)
        {
            objVidoes.LoadInnings(App.Id);
            NavigationService.Navigate(new Uri("/Views/ScoreBoard.xaml?id=" + App.Id, UriKind.Relative));
        }

        private void btnpintostart_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                string chapterNo;
                bool exists = false;
                ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                chapterNo = (selectedListBoxItem.Content as VideoProperties).ChapterNo;
                App.chapterno = App.Id + (selectedListBoxItem.Content as VideoProperties).ChapterNo;
                StandardTileData initialData = new StandardTileData();

                bool img1 = ShellTileHelper.IsPinned(App.chapterno);
                if (img1 == true)
                {
                    ShellTileHelper.UnPin(App.chapterno);

                    var checkSecondaryTileMid = (from v in context.MovieLinks where v.MovieID == int.Parse(App.Id) select v.Title);
                    foreach (var cno in checkSecondaryTileMid)
                    {
                        bool img = ShellTileHelper.IsPinned(App.Id + cno.ToString());
                        if (img == true)
                        {
                            exists = true;
                        }
                    }

                    if (exists == false)
                    {
                        var xquery = (from v in context.VideoList where v.MovieID == int.Parse(App.Id) select v);

                        foreach (var it in xquery)
                        {
                            imgname = it.Image;

                            if (isoStore.FileExists("/Shared/ShellContent/secondary/" + imgname))
                            {
                                isoStore.DeleteFile("/Shared/ShellContent/secondary/" + imgname);
                            }
                        }

                    }
                    objSongList = objVidoes.GetSongsLinksOfAMovie(App.Id, false);
                    LoadSongsLinks(App.Id);
                }
                else
                {


                    var xquery = (from v in context.VideoList where v.MovieID == Convert.ToInt32(App.Id) select v);

                    foreach (var it in xquery)
                    {
                        imgname = it.Image;

                        if (isoStore.FileExists("/" + App.ProjectName + "/Images/" + it.Image))
                        {

                            BitmapImage im = new BitmapImage();
                            im.CreateOptions = BitmapCreateOptions.None;
                            using (IsolatedStorageFileStream local = isoStore.OpenFile("/" + App.ProjectName + "/Images/" + it.Image, FileMode.Open, FileAccess.Read))
                            {

                                im.SetSource(local);
                            }

                            ResizeImage(im);

                        }
                        else
                        {
                            BitmapImage im1 = new BitmapImage();

                            im1.CreateOptions = BitmapCreateOptions.None;

                            Stream s = Application.GetResourceStream(new Uri(App.DirectoryName + "/Images/" + it.Image, UriKind.Relative)).Stream;

                            im1.SetSource(s);
                            ResizeImage(im1);
                        }
                        initialData = new StandardTileData
                        {

                            BackgroundImage = new Uri("isostore:/Shared/ShellContent/secondary/" + it.Image, UriKind.RelativeOrAbsolute),
                            Title = it.Title,
                            BackContent = chapterNo,

                        };
                        Uri uri = new Uri("/Views/CricketDetails.xaml?id=" + App.Id + "&chapter=" + chapterNo + "&id+cno=" + App.chapterno, UriKind.Relative);


                        ShellTileHelper.Pin(uri, initialData);
                        LoadSongsLinks(App.Id);
                        break;




                    }
                }
            }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in btnpintostart_Click Method In CricketDetails.cs file.", ex);
            }
        }
        public void ResizeImage(ImageSource biInput)
        {
            try
            {
                string filePath = string.Empty;
                if (!isoStore.DirectoryExists("Shared/ShellContent/secondary"))
                    isoStore.CreateDirectory("Shared/ShellContent/secondary");
                filePath = imgname;
                if (!isoStore.FileExists("Shared/ShellContent/secondary/" + filePath))
                {

                    WriteableBitmap wbOutput;
                    Image imgTemp = new Image();
                    imgTemp.Source = biInput;

                    wbOutput = new WriteableBitmap(imgTemp, null);
                    using (MemoryStream stream = new MemoryStream())
                    {

                        wbOutput.SaveJpeg(stream, 173, 173, 0, 100);
                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {


                            using (IsolatedStorageFileStream local = myIsolatedStorage.CreateFile("Shared/ShellContent/secondary/" + filePath))
                            {

                                local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                                local.Close();

                            }
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in ResizeImage Method In CricketDetails.cs file.", ex);
            }
        }

        private void imgTitle_MouseEnter(object sender, MouseEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void lbxSongsList_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (chapter != "")
                {
                    IEnumerable<DependencyObject> cboxes = CustomizationSettings.GetChildsRecursive(lbxSongsList);

                    foreach (DependencyObject obj in cboxes.OfType<TextBlock>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "TextBlock")
                        {
                            TextBlock cb = obj as TextBlock;

                            if (cb.Text == chapter)
                            {
                                if (App.ProjectName == "Story Time")
                                    cb.Foreground = new SolidColorBrush(Color.FromArgb(100, 24, 255, 250));
                                else
                                    cb.Foreground = Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush;
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in lbxSongsList_Loaded Method In CricketDetails.cs file.", ex);
            }
        }

      

        private void sharelink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                ShareLinkTask shareLinkTask = new ShareLinkTask();
                shareLinkTask.Title = PhoneHelper.GetAppAttribute("Title") + " App";

                string lnk = " Watch Videos " + (selectedListBoxItem.Content as VideoProperties).ChapterNo + " get app at\n";
                shareLinkTask.Message = lnk;
                shareLinkTask.LinkUri = new Uri("http://www.windowsphone.com/en-US/apps/" + Application.Current.Resources["productid"] as string, UriKind.Absolute);

                shareLinkTask.Show();
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in sharelink_Click Method In CricketDetails.cs file.", ex);
            }

        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                App.detailtocast = 0;
                if (SettingsHelper.getStringValue("CheckDownloadTheme") == "true")
                {
                    if (App.bcount == 1)
                    {
                        e.Cancel = true;
                        gallerypopup.Close();

                    }
                }
                else
                {
                    if (App.bcount == 1)
                    {
                        e.Cancel = true;
                        ratepopup.close();


                    }
                }
                if (YouTube.CancelPlay())
                    e.Cancel = true;
                else
                {

                }
                base.OnBackKeyPress(e);
            }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in OnBackKeyPress Method In CricketDetails.cs file.", ex);
            }
        }

        private void ratelink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                ratepopup.show((selectedListBoxItem.Content as VideoProperties).SongID, (selectedListBoxItem.Content as VideoProperties).MovieId, (selectedListBoxItem.Content as VideoProperties).Rating, "Details");
            }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in ratelink_Click Method In CricketDetails.cs file.", ex);
            }
        }
    }
}

     
